package com.gdcp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gdcp.beans.Category;
import com.gdcp.beans.Product;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.annotation.RedisCache;
import com.gdcp.mapper.ProductMapper;
import com.gdcp.common.page.PageBean;
import com.gdcp.common.page.PageConstants;
import com.gdcp.service.ProductService;
import com.gdcp.util.ImageDto;
import com.gdcp.util.ImageUtil;
import com.gdcp.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ResponseModel responseModel;
    @Autowired
    private ProductMapper productMapper;

    @Override
    @RedisCache(flush = true)
    public List<Product> queryByCreateTime() {
        List<Product> banners=productMapper.queryByCreateTime();
        return banners;
    }

    @Override
    public List<Product> queryByLimit(Integer parent_id, int startRow, int pageSize) {
        List<Product> products=productMapper.queryByLimit(parent_id,startRow,pageSize);
        return products;
    }

    //@Override
    //public int getPageNumber(Integer category_id) {
    //    int totalPageNumber=productMapper.getPageNumber(category_id);
    //    return totalPageNumber;
    //}

    @Override
    public PageBean<Product> findByKeyWord(Integer cid, int pc, String keyword, String sort, Integer min, Integer max) {
        PageBean<Product> pb = new PageBean<>();
        pb.setPc(pc);

        int ps = PageConstants.PRODUCT_PAGE_SIZE;
        pb.setPs(ps);

        //搜索全部，而没有限制
        int tr=productMapper.getPageNumber(cid, min, max).size();
        pb.setTr(tr);

        pb.setTp(pb.getTp());

        List<Product> products=productMapper.findByKeyWord(cid,(pc-1)*ps,ps,keyword,sort, min, max);
        pb.setBeanList(products);
        return pb;
    }

    @Override
    public PageBean<Product> searchByKeyWord(Integer cid, int pc, String search_key, String column, String sort, Integer min, Integer max) {
        PageBean<Product> pb = new PageBean<>();
        pb.setPc(pc);

        int ps = PageConstants.PRODUCT_PAGE_SIZE;
        pb.setPs(ps);

        int tr=productMapper.getPageNumberBySearch(search_key, min, max).size();
        //System.out.println(tr);
        pb.setTr(tr);

        pb.setTp(pb.getTp());
        List<Product> products=productMapper.searchByKeyWord(cid,(pc-1)*ps,ps, search_key, column, sort, min, max);
        pb.setBeanList(products);
        return pb;
    }

    @Override
    public int updateSaleCount(Integer product_id) {
        try{
            productMapper.updateSaleCount(product_id);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int updatePopularity(Integer product_id) {
        try {
            productMapper.updatePopularity(product_id);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    @RedisCache(flush = true)
    public List<Product> queryByPopularity() {
        return productMapper.queryByPopularity();
    }

    @Override
    @RedisCache(flush = true)
    public List<Product> queryBySale_count() {
        return productMapper.queryBySale_count();
    }

    @Override
    public List<Product> queryByParentId(Integer id) {
        return productMapper.queryByParentId(id);
    }

    @Override
    public Map<String, Object> findAll(Map<String, Object> model) {
        Map<String,Object> result = new HashMap<>();
        int total=productMapper.findPageBreakByCondition(null).size();
        List<Product> rows=productMapper.findAll(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>0){
                model.put("a",count);
                rows=productMapper.findAll(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public Map<String, Object> searchInformationByShopId(Map<String, Object> model, Integer shop_id) {
        Map<String,Object> result = new HashMap<>();
        int total=productMapper.searchSizeByShopId(shop_id).size();
        List<Category> rows=productMapper.searchInformationByShopId(model);

        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public void updateInformationByOrderId(Product product) {
        productMapper.updateByPrimaryKey(product);
    }

    @Override
    public Product productInfoById(Integer id) {
        return productMapper.getInformation(id);
    }

    @Override
    @RedisCache(flush = true)
    public List<Product> queryProductsByCid(Integer category_id) {
        return productMapper.queryProductsByCid(category_id);
    }

    @Override
    public List<Product> queryShopProductByShopId(Integer shop_id) {
        return productMapper.queryShopProductByShopId(shop_id);
    }

    @Override
    public Product queryProductByShopId(Integer shop_id) {
        List<Product> products=productMapper.queryProductByShopId(shop_id);
        for(Product product:products){
            return product;
        }
        return null;
    }


    @Override
    public Map<String,Object> findPageBreakByCondition(Map<String, Object> model, Integer shop_id) {
        //bootstrap-table要求服务器返回的json须包含：totlal，rows
        Map<String,Object> result = new HashMap<>();
        int total=productMapper.findPageBreakByConditionByShopId(shop_id).size();
        List<Product> rows=productMapper.findPageBreakByCondition(model);
        if (rows.size()==0){
            int count= (int) model.get("a");
            count=count-(int) model.get("b");
            if (count>0){
                model.put("a",count);
                rows=productMapper.findPageBreakByCondition(model);
            }
        }
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    @Transactional(rollbackFor = { Exception.class })
    public Map<String,Object> removeByPrimaryKey(Integer[] ids) {
        try{
            for (Integer id:ids) {
                productMapper.removeByPrimaryKey(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false,"删除["+ids.length+"条记录失败"+e.toString());
        }

        return responseModel.setModel(true,"成功删除["+ids.length+"条记录");
    }

    @Override
    public Map<String,Object> insert(Product product, ImageDto mainImage, ImageDto imageLeft, ImageDto imageCenter, ImageDto imageRight) {
        return insertImage("insert",product,mainImage,imageLeft,imageCenter,imageRight);
    }

    @Override
    public Map<String,Object> updateInformation(Product product, ImageDto mainImage, ImageDto imageLeft, ImageDto imageCenter, ImageDto imageRight) {
        return insertImage("edit",product,mainImage,imageLeft,imageCenter,imageRight);
    }


    private Map<String,Object> insertImage(String str,Product product, ImageDto mainImage, ImageDto imageLeft, ImageDto imageCenter, ImageDto imageRight){
        //System.out.println(product);
        boolean str_boolean=str.equals("edit");
        Integer url=100;
        if (mainImage!=null){
            if (str_boolean){
                url=product.getId();
            }
            String dest= PathUtil.getShopImagePath(url);

            try {
                String imageAddr = ImageUtil.generateThumbnail(mainImage, dest);
                product.setMain_image(imageAddr);
            } catch (Exception e) {
                e.printStackTrace();
                return responseModel.setModel(false,"获取图片失败");
            }
        }

        String js=product.getSub_images();
        if (str_boolean){
            Product originalProduct=productMapper.getInformation(product.getId());
            js=originalProduct.getSub_images();
        }

        String imageLeftAddr = "";
        String imageCenterAddr = "";
        String imageRightAddr = "";

        if (str.equals("edit")){
            url=product.getId();
        }

        JSONObject jsonObj = null;
        //修改本身有路径的
        if (str_boolean&&js.indexOf('\\')>0){
            String json=js.replaceAll("\\\\", "\\\\\\\\");
            jsonObj = JSONObject.parseObject(json);
        }

        //修改:有路径、无路径；有路径：修改一个不是全部。
        //添加:无路径，可能只添加一个。
        String dest=PathUtil.getShopImagePath(url);
        if (imageLeft!=null){
            try {
                imageLeftAddr = ImageUtil.generateThumbnail(imageLeft,dest);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return responseModel.setModel(false,"获取图片失败");
            }
        }else {
            if (str_boolean&&jsonObj!=null){
                imageLeftAddr = jsonObj.getString("image_left");
            }
        }

        if (imageCenter!=null){
            try {
                imageCenterAddr = ImageUtil.generateThumbnail(imageCenter,dest);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return responseModel.setModel(false,"获取图片失败");
            }
        }else {
            if (str_boolean&&jsonObj!=null) {
                imageCenterAddr = jsonObj.getString("image_center");
            }
        }

        if (imageRight!=null){
            try {
                imageRightAddr = ImageUtil.generateThumbnail(imageRight,dest);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return responseModel.setModel(false,"获取图片失败");
            }
        }else {
            if (str_boolean&&jsonObj!=null) {
                imageRightAddr = jsonObj.getString("image_right");
            }
        }

        String sub_images="{\"image_left\":\""+imageLeftAddr
                +"\",\"image_center\":\""+imageCenterAddr
                +"\",\"image_right\":\""+imageRightAddr
                +"\"}";
        product.setSub_images(sub_images);

        if (str_boolean){
            //System.out.println(product);
            try {
                productMapper.updateByPrimaryKey(product);
                return responseModel.setModel(true,"修改成功");
            }catch (Exception e){
                e.printStackTrace();
                return responseModel.setModel(false,"修改失败");
            }
        }else {
            try {
                productMapper.insert(product);
                return responseModel.setModel(true,"添加成功");
            }catch (Exception e){
                e.printStackTrace();
                return responseModel.setModel(false,"添加失败");
            }
        }
    }

    @Override
    public Product getInformation(Integer id) {
        return productMapper.getInformation(id);
    }

    @Override
    public Map<String, Object> searchInformation(Map<String, Object> param) {
        Map<String,Object> result = new HashMap<>();
        int total=productMapper.searchInformation(null).size();
        List<Product> rows=productMapper.searchInformation(param);
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public List<Product> queryAllByShopId(Integer shopId) {
        return productMapper.queryAllByShopId(shopId);
    }
}
